# Audio API endpoints
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from typing import Optional

from ...core.auth import get_current_user
from ...core.config import NovelProject
from ...models.user import User
from ...services.tts_service import tts_service
import logging

logger = logging.getLogger(__name__)
router = APIRouter()


class TTSRequest(BaseModel):
    text: str = Field(..., min_length=1, max_length=500, description="要转换的文本")
    character_name: str = Field(..., description="角色名称")
    novel_project: str = Field(..., description="小说项目")
    role_type: Optional[str] = Field("supporting", description="角色类型")
    gender: Optional[str] = Field(None, description="角色性别 (male/female)")
    effects: Optional[dict] = Field(None, description="音频效果配置")


class TTSResponse(BaseModel):
    audio_url: str = Field(..., description="语音文件URL")
    character_name: str = Field(..., description="角色名称")
    text: str = Field(..., description="转换的文本")
    voice_config: Optional[dict] = Field(None, description="使用的语音配置")


@router.get("/processor-status")
async def get_audio_processor_status(
    current_user: User = Depends(get_current_user)
):
    """获取音频处理器状态"""
    try:
        status_info = tts_service.get_available_voices()
        return {
            "code": 200,
            "message": "获取音频处理器状态成功",
            "data": status_info
        }
    except Exception as e:
        logger.error(f"获取音频处理器状态失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取音频处理器状态失败"
        )


@router.get("/voices")
async def get_voice_configs(current_user: User = Depends(get_current_user)):
    """获取所有角色的语音配置"""
    try:
        characters = [
            "萧炎", "薰儿", "药尘", "唐三", "小舞", "大师", 
            "张小敬", "李必"
        ]
        
        voice_configs = {}
        for character in characters:
            voice_configs[character] = tts_service.get_character_voice_info(
                character
            )
        
        # 添加音频处理器状态信息
        processor_status = tts_service.get_available_voices()
        
        return {
            "code": 200,
            "message": "获取语音配置成功",
            "data": {
                "characters": voice_configs,
                "audio_processor": processor_status
            }
        }
    except Exception as e:
        logger.error(f"获取语音配置失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取语音配置失败"
        )


@router.post("/tts", response_model=TTSResponse)
async def text_to_speech(
    request: TTSRequest,
    current_user: User = Depends(get_current_user)
):
    """文字转语音"""
    try:
        # 验证小说项目
        try:
            novel_project = NovelProject(request.novel_project)
        except ValueError:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"不支持的小说项目: {request.novel_project}"
            )
        
        # 如果没有提供性别，尝试基于角色名称推断
        gender = request.gender
        if not gender:
            gender = tts_service._infer_gender_from_name(
                request.character_name
            )
        
        # 调用TTS服务
        audio_url = await tts_service.text_to_speech(
            text=request.text,
            character_name=request.character_name,
            novel_project=novel_project,
            role_type=request.role_type or "supporting",
            gender=gender or "male",
            effects=request.effects
        )
        
        if not audio_url:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="语音生成失败"
            )
        
        # 获取使用的语音配置信息
        voice_info = tts_service.get_character_voice_info(
            request.character_name
        )
        
        return TTSResponse(
            audio_url=audio_url,
            character_name=request.character_name,
            text=request.text,
            voice_config=voice_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"TTS API调用失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="语音生成服务暂时不可用"
        ) 